#!/usr/bin/env python3

#
# $Id$
#
# This simple script tries to convert regular verbs into past simple tense.
# In some ambiguous cases the program will ask you for correct answer.
#

import sys
import os
import re

def is_vowel(letter):
    if letter in 'aeiou':
        return True
    else:
        return False

def is_consonant(letter):
    return not is_vowel(letter)

def ask_user_past_simple_of(verb):
    try:
        return input('Past simple of ' + verb + ':')
    except EOFError:
        sys.exit(0)

def ask_user_either_or(verb, form1, form2):
    try:
        while True:
            answer = input('Which form of ' + verb + ' is correct: ' + form1 + ' (1) or ' + form2 + ' (2)?')
            if answer == '1':
                return form1
            elif answer == '2':
                return form2
            else:
                continue
    except EOFError:
        sys.exit(0)

def get_number_of_syllables(word):
    # hello -> CVCCV
    word_map = ''.join(list(map(lambda x: 'V' if is_vowel(x) else 'C', word)))

    # VVVCCCVVVCCC -> VCVC
    word_map = re.sub('C+', 'C', word_map)
    word_map = re.sub('V+', 'V', word_map)

    # number of V's = number of syllables
    number_of_syllables = sum(list(map(lambda x: 1 if x == 'V' else 0, word_map)))

    return number_of_syllables

def convert_verb_to_past_simple(verb):
    if verb == 'pay':
        return 'paid'
    elif verb == 'lay':
        return 'laid'
    elif verb == 'say':
        return 'said'

    if is_vowel(verb[-2]) and verb[-1] == 'y':
        return verb + 'ed'
    elif is_consonant(verb[-2]) and verb[-1] == 'y':
        return verb[:-2] + 'ied'
    elif verb[-1] == 'e':
        return verb + 'd'
    elif is_consonant(verb[-3]) and is_vowel(verb[-2]) and is_consonant(verb[-1]):
        if verb[-1] == 'w' or verb[-1] == 'x' or verb[-1] == 'y':
            return verb + 'ed'
        else:
            if get_number_of_syllables(verb) == 1:
                return verb + verb[-1] + 'ed'
            else:
                return ask_user_either_or(verb, verb + 'ed', verb + verb[-1] + 'ed')
    elif is_consonant(verb[-1]):
        return verb + 'ed'

    return ask_user_past_simple_of(verb)

def main():
    if len(sys.argv) != 3:
        print('Usage:', sys.argv[0], 'input_file', 'output_file')
        sys.exit(0)

    input_file = open(sys.argv[1], 'r')
    output_file = open(sys.argv[2], 'w')

    for verb in input_file:
        verb = verb.rstrip(os.linesep)

        if len(verb) < 3:
            continue

        output_file.write(convert_verb_to_past_simple(verb.lower()) + "\n")

    return

main()
